package controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.FollowerDao;
import model.FollowingDao;
import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA
 * Description
 * User：chenshu
 * Date：2023-12-24
 * Time：22:26
 */
@WebServlet("/userlist")
public class UserListServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf8");
        List<User> users = null;
        String jsonStr = null;
        UserDao userDao = new UserDao();
        String userId = req.getParameter("userId");
        String author = req.getParameter("author");
        if (userId == null && author == null) {
            //无参代表管理员查询用户列表，返回所有用户
            users = userDao.selectAll();
            jsonStr = objectMapper.writeValueAsString(users);
            resp.getWriter().write(jsonStr);
        } else {
            //有参代表用户查询他的关注列表，返回所有关注
            users = new ArrayList<>();
            List<Integer> userIdList = new ArrayList<>();
            FollowingDao followingDao = new FollowingDao();
            FollowerDao followerDao = new FollowerDao();
            if (userId != null) {
                int uId = Integer.parseInt(userId);
                userIdList = followingDao.selectFollowing(uId);
            } else {
                int authorId = Integer.parseInt(author);
                userIdList = followerDao.selectFollowers(authorId);
            }
            for (Integer i : userIdList) {
                users.add(userDao.selectById(i));
            }
            jsonStr = objectMapper.writeValueAsString(users);
            resp.getWriter().write(jsonStr);
        }

    }
}
